/** 
 * @function 接口地址
 */
// export const baseUrl = 'http://1.14.14.210:8080'
export const baseUrl = 'https://tripknow.cn'
/** 
 * @function 图片地址
 */
// export const imgUrl = 'http://1.14.14.210/';
export const imgUrl = 'https://tripknow.cn/';

class Model {
	//定义接口
	api(opts = {}) {
		//监听网络链接
		uni.onNetworkStatusChange((res) => {
			if (!res.isConnected) {
				uni.showToast({
					title: '网络连接不可用！',
					icon: 'none',
					duration: 1500
				});
			}
			return false
		});
		//定义参数对象
		if (!opts.method) opts.method = 'get'
		// 鉴权
		let authorize = ''
		if (uni.getStorageSync('token')) authorize = uni.getStorageSync('token')

		let header = {
			token: authorize,
			'Content-Type': 'application/json; charset=UTF-8'
		}

		if (opts.data && opts.data.action) {
			header = {
				...header,
				action: opts.data.action
			}
		}

		// 删除鉴权
		if (opts.noAuth) {
			delete header.Authorization
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + opts.url,
				data: opts.data,
				method: opts.method,
				header: header,
				success: res => {
					uni.hideLoading();
					if (res.data.code === "10000") {
						resolve(res.data)
					} else if (res.data.code === "10009" || res.data.code === "10008") {
						uni.removeStorageSync('token');

						uni.showToast({
							title: '请登录后操作！',
							icon: 'none',
							duration: 1500
						});

						// setTimeout(() => {
							// uni.navigateTo({
							// 	url: '/pages/login/login'
							// })
						// }, 1500)
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
						});
						reject(res.data)
					}
				},
				fail: err => {
					uni.hideLoading();
					// uni.showToast({
					// 	title: '请求失败,请稍候重试',
					// 	icon: 'none',
					// 	duration: 1500
					// });
				}
			});
		})
	}

	get(url, options = {}) {
		let u = [],
			url_other = '';
		for (let key in options) {
			let d = `${key}=${options[key]}`;
			u.push(d);
		}
		if (u.length) url_other = `?${u.join('&')}`
		options.url = url + url_other;
		options.method = 'GET';
		return this.api(options)
	}
	post(url, options = {}) {
		let params = {
			method: 'POST',
			url: url,
			data: options
		}
		return this.api(params)
	}
	delete(url, options = {}) {
		let params = {
			method: 'DELETE',
			url: url,
			data: options
		}
		return this.api(params)
	}
	put(url, options = {}) {
		let params = {
			method: 'PUT',
			url: url,
			data: options
		}
		return this.api(params)
	}

}

export default Model;
